package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.item.dto.SpecGroupDTO;
import com.leyou.item.dto.SpecParamDTO;
import com.leyou.item.entity.SpecGroup;
import com.leyou.item.mapper.SpecGroupMapper;
import com.leyou.item.service.SpecGroupService;
import com.leyou.item.service.SpecParamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class SpecGroupServiceImpl extends ServiceImpl<SpecGroupMapper, SpecGroup> implements SpecGroupService {
   @Autowired
   private SpecParamService specParamService;
    @Override
    public List<SpecGroupDTO> querySpecGroupCategoryId(Long cid) {

        return SpecGroupDTO.convertEntityList(
                query()
                        .eq("category_id",cid)
                        .list()
        );
    }

    @Override
    public List<SpecGroupDTO> querySpecList(Long cid) {
        //根据分类查询对应的规格参数组集合
        List<SpecGroupDTO>specGroupDTOS=querySpecGroupCategoryId(cid);
        //一次性查询出  当前分类下所有的规格参数
        List<SpecParamDTO>specParamDTOS=this.specParamService.queryParams(null,cid,null);
        //对规格参数的查询结果进行分组，分组的条件为groupId  获取到一个map key为groupId，value是同groupId对应的所有的值
        Map<Long,List<SpecParamDTO>>collect=specParamDTOS
                .stream()
                .collect(
                        Collectors.groupingBy(
                                SpecParamDTO::getGroupId));
        //给规格参数组中的每个对应的规格参数赋值
        for (SpecGroupDTO specGroupDTO : specGroupDTOS) {
            specGroupDTO.setParams(collect.get(specGroupDTO.getId()));
        }
        return specGroupDTOS;
    }
}
